﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;


namespace MengRan.Controllers.api
{
    [ApiController]
    [Route("Home/api/[controller]/[action]")]
    
    public class ptoController : Controller
    {
        public  IActionResult chuan([FromForm] IFormFile file)
        {
           
            string physicalFilePath = hostingEnv.WebRootPath;
            string dirPath = physicalFilePath + "\\" + "image" + "\\";
           
           var  fileName =  dirPath + file.FileName;
            using (FileStream fileS = new FileStream(fileName, FileMode.Create))
            {
                 file.CopyTo(fileS);
                fileS.Flush();//关闭流

            }
            return Ok(new { code = 0 });
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpLoad(IFormFile file)
        {
            Request.Cookies.TryGetValue("size", out string val);//获取cookie

            //压缩处理
            Image img = ReadStreamToImage(file);
            Bitmap bmp1 = (Bitmap)img;
            ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            long a = 0;
            if (val != null)
            {
                 a = long.Parse(val);
            }
            else {
                 a = 20;
            };
            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, a);
            myEncoderParameters.Param[0] = myEncoderParameter;

            string physicalFilePath = hostingEnv.WebRootPath;
            string dirPath = physicalFilePath + "\\" + "image" + "\\";
            string suijishu = Math.Abs(Guid.NewGuid().GetHashCode()).ToString();
            String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_" + suijishu, DateTimeFormatInfo.InvariantInfo) + ".jpg";//fileExt;
            string fileName = dirPath + $@"{newFileName}";
            //var fileName = Directory.GetCurrentDirectory()+"/image/"+file.FileName; ///Directory.GetCurrentDirectory()获取项目所在文件夹
            bmp1.Save(@fileName, jpgEncoder, myEncoderParameters);//保存图片
            //保存 fileStream这个对象是文件流 其中我们传入保存路径以及文件新建方式 
            //using (FileStream fileS = new FileStream(fileName, FileMode.Create))
            //{
            //   await file.CopyTo(fileS);
            //    fileS.Flush();//关闭流
            //}
            var url = "/" + "Image" + "/" + newFileName;
            return Ok(new { code = 0 , urle = url, });
        }
        private IHostingEnvironment hostingEnv;
        public ptoController(IHostingEnvironment hostingEnv)
        {
            this.hostingEnv = hostingEnv;
        }
        private static Image ReadStreamToImage(IFormFile file)
        {
            var length = (int)file.Length;
            var stream = file.OpenReadStream();
            var imageBytes = new byte[length];
            stream.Read(imageBytes, 0, length);
            return Image.FromStream(stream);
        }
        private ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }

            return null;
        }
    }
}
